//
//  LCBibleTableViewController.m
//  自适应TableView布局
//
//  Created by jiukuyinyue on 2017/10/12.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCBibleTableViewController.h"
#import "UITableView+SDAutoTableViewCellHeight.h"
#import "LCLrcLine.h"
#import "LCBibleTableViewCell.h"
#import "TheHomeManager+Additions.h"
#import "LCLrcAnalyzer.h"
#import "JKSongsMessStatus.h"
#import "NSString+Substring.h"
#import "LCHistoryDataManager.h"
#import "LCCommentsNum.h"

#define cellID @"cellID"
@interface LCBibleTableViewController ()<UIScrollViewDelegate>

@property (nonatomic,weak) LCBibleTableViewCell *cell;
@end

@implementation LCBibleTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //    [[LCWebServicesManager sharedInstance] getTagNumWithShengJingTitle:song.title success:^(NSDictionary *dict) {
    //        NSLog(@"dict = %@", dict);
    //        NetWorkModel *netWorkModel = [NetWorkModel yy_modelWithJSON:dict];
    //        netWorkModel;
    //    } failure:^(NSError *error) {
    //
    //    }];
    
    self.selectedData = [NSMutableArray array];
    
    [self setupNotifications];
    self.view.backgroundColor = [UIColor clearColor];
    self.tableView.backgroundColor = [UIColor clearColor];/** 去除tableview 背景颜色 透明 */
    self.tableView.showsVerticalScrollIndicator = NO;/** 去除tableview 右侧滚动条 */
    self.tableView.separatorStyle = NO;/** 去除tableview cell线 */
    
    [self.tableView registerClass:[LCBibleTableViewCell class] forCellReuseIdentifier:cellID];
    self.tableView.allowsSelection = YES;//允许多选
    self.tableView.allowsMultipleSelection = YES;
    //添加以下代码关闭估算行高
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    _indexPathArr = [NSMutableArray array];
}
//-(void)setupHeaderView{
//    UIView *headView = [[UIView alloc] init];
////    CGFloat height = 200;
//
////    UILabel *label = [[UILabel alloc] init];
//
////    [headView addSubview:self.cycleScrollView];
//
//    self.tableView.tableHeaderView = headView;
//}

- (void)setupNotifications {
    // 1. 安装播放状态发生变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerCurrentTimeDidChangedNotification:) name:LCMusicPlayerCurrentTimeDidChangedNotification object:_LCPlayer];
    // 2.歌曲发生变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(musicPlayerPlayingSongDidChangedNotification:) name:LCMusicPlayerPlayingSongDidChangedNotification object:_LCPlayer];
    // 3.ziti 变化的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"BIBLETEXTFONT" object:nil];
    
}
- (void)dealloc
{
    [self teardownNotifications];
}
- (void)teardownNotifications {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)musicPlayerCurrentTimeDidChangedNotification:(NSNotification *)notification {
    NSTimeInterval currentTime = [notification.userInfo[kCurrentTime] floatValue];
    NSTimeInterval totalTime = [notification.userInfo[kTotalTime] floatValue];
    if (self.isDragging == NO) {
        [self refreshUIWithCurrentTime:currentTime totalTime:totalTime];
    }
    
}
// 通过播放的当前时间和总共时间刷新UI
- (void)refreshUIWithCurrentTime:(float)currentTime totalTime:(float)totalTime {
    // 更新歌词UI
    [self playControlLrcWithCurrentTime:currentTime totalTime:totalTime];
}

///歌词控制 监测播放进度
- (void)playControlLrcWithCurrentTime:(float)currentTime totalTime:(float)totalTime{
    
    if (!self.isDragging) {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            //歌词滚动显示
            for ( int i = (int)(self.lrcArray.count - 1); i >= 0 ;i--) {
                LCLrcLine * lrc = self.lrcArray[i];
                if (lrc.time < currentTime) {
                    
                    self.currentRow = i;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        
                        [UIView animateWithDuration: 0.3 animations: ^{
                            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow: self.currentRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:NO];
                        } completion:^(BOOL finished) {
                            [self.tableView reloadData];
                        }];
                    });
                    break;
                }
            }
        });
        
    }
    
}


#pragma mark - tableview datasourece and delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.lrcArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LCLrcLine * lrcLine = _lrcArray[indexPath.row];
    
    LCBibleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    _cell = cell;
    if (!cell) {
        cell = [[LCBibleTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    JKSongsMessStatus *playingSong = [JKSongsMessStatus yy_modelWithJSON:[LCHistoryDataManager loadBibleTextData]];
    NSString *str = playingSong.title;
    str = [str substringWithinBoundsLeft:@"第" right:@"章"];
    
    cell.titleLabel.text = [NSString stringWithFormat:@"%@:%zd",str,indexPath.row+1];
    cell.contentLabel.text = [NSString stringWithFormat:@"%@",lrcLine.lrc];
    cell.contentButton.hidden = !lrcLine.commentsNum;
    [cell.contentButton setTitle:[NSString stringWithFormat:@"%@评",lrcLine.commentsNum] forState:(UIControlStateNormal)];
    if (self.currentRow == indexPath.row) {
        cell.contentLabel.textColor = [UIColor redColor];
    }else{
        cell.contentLabel.textColor = [UIColor blackColor];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    cell.backgroundColor = [UIColor clearColor];
    @weakify(self)
    cell.pushShowComposeVCBlock = ^(NSString *titleStr, NSString *contentStr) {
        @strongify(self)
        if (self.pushShowComposeVCBlock != nil) {
            self.pushShowComposeVCBlock(titleStr,contentStr);
        }
    };
    //    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
    //    cell.selectedBackgroundView.backgroundColor = [UIColor orangeColor];
    
    
    NSString * strNow = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
    //    NSLog(@"%@",strNow);
    //    NSLog(@"%ld<<<<<<<个数",(long)self.indexPathArr.count);
    for (NSInteger i = 0; i < self.indexPathArr.count; i++) {
        NSString * strRow = [NSString stringWithFormat:@"%@",self.indexPathArr[i]];
        if ([strNow isEqualToString:strRow]) {
            cell.backgroundColor = RGBColor(254, 221, 221);
            return cell;
            //            NSLog(@"%ld",indexPath.row);
        }else{
            cell.backgroundColor = [UIColor clearColor];
        }
    }
    return cell;
    
}
//选中
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    LCLrcLine * lrcLine = _lrcArray[indexPath.row];
    JKSongsMessStatus *playingSong = [JKSongsMessStatus yy_modelWithJSON:[LCHistoryDataManager loadBibleTextData]];
    NSString *str = playingSong.title;
    str = [str substringWithinBoundsLeft:@"第" right:@"章"];
    str = [NSString stringWithFormat:@"%@:%zd %@",str,indexPath.row + 1,lrcLine.lrc];
    [self.selectedData addObject:str];
    //点击方
    if (_collectionBlock != nil) {
        _collectionBlock();
    }
    
    NSString * strRowNow = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
    
    
    for (NSInteger i = 0; i < self.indexPathArr.count; i++) {
        
        NSString * strRow = [NSString stringWithFormat:@"%@",self.indexPathArr[i]];
        if ([strRow isEqualToString:strRowNow]) {
            [self.indexPathArr removeObject:strRow];
            LCLrcLine * lrcLine = _lrcArray[[strRow integerValue]];
            NSString *str = playingSong.title;
            str = [str substringWithinBoundsLeft:@"第" right:@"章"];
            str = [NSString stringWithFormat:@"%@:%zd %@",str,indexPath.row + 1,lrcLine.lrc];
            [self.selectedData removeObject:str];
            
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
            return;
        }
    }
    [self.indexPathArr addObject:strRowNow];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
    
}

//- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
//    LCLrcLine * lrcLine = _lrcArray[indexPath.row];
//    NSString *str = _LCPlayer.playingSong.title;
//    str = [str substringWithinBoundsLeft:@"第" right:@"章"];
//    str = [NSString stringWithFormat:@"%@:%zd %@",str,indexPath.row + 1,lrcLine.lrc];
//
//    [self.selectedData removeObject:str];
//}

#pragma mark - 通知处理回调
-(void)receiveNotification:(NSNotification *)notification{
    if (_cell) {
        [_cell receiveNotification:notification];
    }
    [self.tableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = [self cellHeightForIndexPath:indexPath cellContentViewWidth:[UIScreen mainScreen].bounds.size.width];
    return height;
}

-(void)setLrcArray:(NSArray *)lrcArray{
    _lrcArray = lrcArray;
    
    [self.tableView reloadData];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    _isDragging = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSLog(@"scrollViewDidEndDecelerating ");
        self.isDragging = NO;
    });
}
- (void)musicPlayerPlayingSongDidChangedNotification:(NSNotification *)notification {
    JKSongsMessStatus *playingSong = notification.userInfo[kMusicPlayerPlayingSong];
    [self refreshUIWithSong:playingSong];
}

- (void)refreshUIWithSong:(JKSongsMessStatus *)song {
    // 歌词面板更新
    [self lrcWordWithID:song];
}


- (void)lrcWordWithID:(JKSongsMessStatus *)song {
    
    NSString *sid = song.fileUrl;
    if (sid == nil) {
        //        sid = @"mp3hot.9ku.comhot201307-11543970.mp3";
        NSDictionary *json = @{
                               @"duration" : @(341000),
                               @"fileUrl" : @"http://mp3hot.9ku.com/hot/2013/07-11/543970.mp3",
                               @"id" : @(1),
                               @"singerName" : @"圣经旧约",
                               @"title" : @"旧约创世记(创)第1章"
                               };
        song = [JKSongsMessStatus yy_modelWithJSON:json];
        sid = song.fileUrl;
    }
    
    sid = [sid stringByReplacingOccurrencesOfString:@"http://" withString:@""];
    sid = [sid stringByReplacingOccurrencesOfString:@"/" withString:@""];
    
    NSString *str = [[TheHomeManager shareTheHomeManager] getShengJingLrc:[song.id integerValue]];
    [self getLrcArrayWithPath:[self downloadKlrcWithStr:str newStr:sid]];//获得歌词数组
}
//获得歌词数组
- (void)getLrcArrayWithPath:(NSString *)path{
    LCLrcAnalyzer *  analyzer = [[LCLrcAnalyzer alloc] init];
    self.lrcArray =  [analyzer analyzerLrcBylrcString:[NSString  stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]];
    ///获得评论数量
    @weakify(self)
    [[LCWebServicesManager sharedInstance] getTagNumWithShengJingTitle:_LCPlayer.playingSong.title success:^(NSDictionary *dict) {
        @strongify(self)
        NetWorkModel *netWorkModel = [NetWorkModel yy_modelWithJSON:dict];
        LCCommentsNum *commentsNum = [LCCommentsNum yy_modelWithJSON:netWorkModel.data];
        NSLog(@"commentsNum.row = %@", commentsNum.row);
        NSMutableArray *mutableArray = [NSMutableArray array];
        for (NSInteger i = 0; i < self.lrcArray.count; i++) {
            LCLrcLine *lrcLine = self.lrcArray[i];
            if ([commentsNum.row objectForKey:[NSString stringWithFormat:@"%zd",i+1]]) {
                lrcLine.commentsNum = commentsNum.row[[NSString stringWithFormat:@"%zd",i+1]];
            }
            [mutableArray addObject:lrcLine];
        }
        self.lrcArray = mutableArray.copy;
        
    } failure:^(NSError *error) {
        NSLog(@"error = %@", error);
    }];
}

//下载歌词
-(NSString *)downloadKlrcWithStr:(NSString *)fileStr newStr:(NSString *)newStr{
    NSString *filePath = [self lrcWithNewStr:newStr];
    [fileStr writeToFile:filePath atomically:YES  encoding:NSUTF8StringEncoding error:nil];
    return filePath;
}
//歌词沙盒路径
-(NSString *)lrcWithNewStr:(NSString *)newStr{
    NSString *lrcDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.lrc", lrcDirPath ,newStr];
    return filePath;
}
//判断下载的文件是否已经在沙盒中已经存在？
-(BOOL) isFileExist:(NSString *)fileName{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:fileName];
    NSLog(@"：%@",result?@"歌词存在":@"歌词不存在");
    return result;
}

@end
